package com.hydong.novatest.activity

import android.app.ProgressDialog
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.google.gson.Gson
import com.hydong.novatest.R
import com.hydong.novatest.adapter.StarAdapter
import com.hydong.novatest.base.BaseApp
import com.hydong.novatest.base.Constants
import com.hydong.novatest.entity.CometJsonBean
import com.hydong.novatest.entity.StarObject
import com.hydong.novatest.entity.StarRecordBean
import kotlinx.android.synthetic.main.activity_star.*
import org.json.JSONArray
import java.io.File

class StarActivity : AppCompatActivity() {
    var pd: ProgressDialog? = null

    var starObject: StarAdapter? = null

    private fun initAdapter() {
        starObject = StarAdapter(ArrayList())
        recycler_view.layoutManager = LinearLayoutManager(this)
        recycler_view.adapter = starObject
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_star)

        // 初始化语言
        val language: String = resources.configuration.locale.language
        Constants.isChineseEnv = language.endsWith("zh")

        initAdapter()

        // 删除DB
        btn_drop_db?.setOnClickListener {
            CleanUtils.cleanInternalDbs();
        }

        // 拷贝DB
        btn_copy_db?.setOnClickListener {
            copyDb()
        }

        // 插入彗星
        btn_insert_comet?.setOnClickListener {
            insertComet()
        }

        // 插入太阳系
        btn_calc_solar?.setOnClickListener {
            insertSolar()
        }

        // 计算所有星体
        btn_calc_all?.setOnClickListener {
            calcAllStars()
        }
    }

    /**
     * 拷贝数据库
     */
    private fun copyDb() {
        showProgressDialog("拷贝中")
        val start = System.currentTimeMillis()
        Thread(Runnable {
            var assetsFilePath: String = Constants.STARS_DB_NAME
            var destFilePath: String = PathUtils.getInternalAppDbsPath() + File.separator + Constants.STARS_DB_NAME
            val isSuccess = ResourceUtils.copyFileFromAssets(assetsFilePath, destFilePath)
            if (isSuccess) {
                // 拷贝完成
                ThreadUtils.runOnUiThread {
                    val coast = System.currentTimeMillis() - start
                    tv_time?.text = "拷贝DB $coast ms"
                    dismissProgressDialog()
                }
            } else {
                // 拷贝失败
                ThreadUtils.runOnUiThread {
                    tv_time?.text = "拷贝失败"
                    dismissProgressDialog()
                }
            }
        }).start()
    }

    /**
     * 插入太阳系
     */
    private fun insertSolar() {
        ToastUtils.showShort("TODO")
    }

    /**
     * 插入彗星
     */
    private fun insertComet() {
        showProgressDialog("插入中")
        val start = System.currentTimeMillis()
        Thread(Runnable {
            var jsonComet: String = ResourceUtils.readAssets2String("comet.json")
            val daoSession = (application as BaseApp).daoSession
            var length = 0
            try {
                val jsonArray = JSONArray(jsonComet)
                length = jsonArray.length()
                for (i in 0 until length) {
                    val item = Gson().fromJson(jsonArray[i].toString(), CometJsonBean::class.java)
                    val bean = StarRecordBean(Constants.STAR_COMET, item.name, item.mag, item.ra, item.dec, item.size)
                    daoSession.insertOrReplace(bean)
                }

                ThreadUtils.runOnUiThread {
                    val coast = System.currentTimeMillis() - start
                    tv_time?.text = "插入 $length 条,耗时 $coast ms"
                    dismissProgressDialog()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                ThreadUtils.runOnUiThread {
                    val coast = System.currentTimeMillis() - start
                    tv_time?.text = "插入失败,耗时 $coast ms"
                    dismissProgressDialog()
                }
            }
        }).start()
    }

    /**
     * 计算所有星体
     */
    private fun calcAllStars() {
        showProgressDialog("计算中")
        var start = System.currentTimeMillis()
        var dbCoast = 0L

        Thread(Runnable {
            val daoSession = (application as BaseApp).daoSession
            val dao = daoSession.starRecordBeanDao

            // item -> javaBean
            var starList: MutableList<StarRecordBean> = ArrayList()
            try {
                starList = dao.loadAll()

                dbCoast = System.currentTimeMillis() - start
                start = System.currentTimeMillis()

                val starObjectList: MutableList<StarObject> = ArrayList()
                starList.forEach {
                    starObjectList.add(StarObject(it))
                }

                // 计算
                starObjectList.forEach {
                    var info = "";
                    info += "Name: ${it.name}\n"
                    info += "RA: ${it.raJnowStr}\n"
                    info += "DEC: ${it.decJnowStr}\n"

//                    var list: List<LnHrzPosn> = it.altitudeList;
//                    list.forEachIndexed { index, lnHrzPosn ->
//                        info += "[#$index]-${lnHrzPosn.alt}   ";
//                    }
                    Log.d("DHY__", info);
                }

                ThreadUtils.runOnUiThread {
                    // 加载列表
                    starObject?.setList(starObjectList)

                    val coast = System.currentTimeMillis() - start
                    tv_time?.text = "计算 ${starList.size} 条, 查询耗时 $dbCoast ms, 计算耗时 $coast ms"
                    dismissProgressDialog()
                }

            } catch (e: Exception) {
                e.printStackTrace()
                ThreadUtils.runOnUiThread {
                    val coast = System.currentTimeMillis() - start
                    tv_time?.text = "查询失败,耗时 $coast ms"
                    dismissProgressDialog()
                }
            }
        }).start()
    }


    // =====================================
    private fun showProgressDialog(msg: String) {
        pd = ProgressDialog(this)
        pd?.setMessage(msg)
        pd?.setCancelable(false)
        pd?.show()
    }

    private fun dismissProgressDialog() {
        pd?.dismiss()
    }
}